package handler

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"user-sys0/models"
)

func UserRoleAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	if uid == 0 || rid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	userRole := models.UserRole{
		Uid: uid,
		Rid: rid,
	}
	models.DB.Create(&userRole)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	if rid == 0 || nid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	roleNode := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	models.DB.Create(&roleNode)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func UserRoleList(c *gin.Context) {
	uid := c.Query("uid")
	/*
			SELECT
			  *
			FROM
			  roles
			  LEFT JOIN user_roles ON user_roles.rid = roles.id
		WHERE
		  user_roles.rid = 1
	*/
	var userRole []models.Role
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid = roles.id").
		Where("user_roles.uid = ?", uid).Find(&userRole)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": userRole,
	})
	return

}
func RoleNodeList(c *gin.Context) {
	rid := c.Query("rid")
	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
		WHERE
		  role_nodes.rid = 1
	*/

	var roleNode []models.Node
	models.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where("role_nodes.rid = ?", rid).Find(&roleNode)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": roleNode,
	})
	return
}
